import {getHotKeywordsData,getSearchGoodsData} from "../../api/search";
export default {
    namespaced:true,
    state:{
        //搜索的关键词
        keywords:"",
        //历史搜索关键词
        historyKeywords:uni.getStorageSync("historyKeywords")?JSON.parse(uni.getStorageSync("historyKeywords")):[],
        //热门搜索关键词
        hotKeywords:[],
        searchGoods:[]//搜索菜品的数据
    },
    mutations:{
        //设置搜索关键词
        ["SET_KEYWORDS"](state,payload){
            state.keywords=payload.keywords;
        },
        //设置历史搜索关键词
        ["SET_HISTORY_KEYWORDS"](state,payload){
            if(payload.keywords){
                for(let i=0;i<state.historyKeywords.length;i++){
                    if(state.historyKeywords[i]==payload.keywords){
                        state.historyKeywords.splice(i--,1);
                        break;
                    }
                }
                state.historyKeywords.unshift(payload.keywords);
                uni.setStorageSync("historyKeywords",JSON.stringify(state.historyKeywords))
            }
        },
        //清除历史关键词
        ["CLEAR_HISTORY_KEYWORDS"](state){
            state.historyKeywords=[];
            uni.removeStorageSync("historyKeywords");
        },
        //设置热门搜索关键词
        ["SET_HOT_KEYWORDS"](state,payload){
            state.hotKeywords=payload.hotKeywords;
        },
        //设置搜索菜品的数据
        ["SET_SEARCH_GOODS"](state,payload){
            state.searchGoods=payload.searchGoods;
        },
        //设置搜索菜品的分页数据
        ["SET_SEARCH_GOODS_PAGE"](state,payload){
            state.searchGoods.push(...payload.searchGoods);
        }
    },
    actions:{
        getHotKeywords(conText,payload){
            getHotKeywordsData().then(res=>{
                if(res.code==200){
                    conText.commit("SET_HOT_KEYWORDS",{hotKeywords:res.data});
                }else{
                    conText.commit("SET_HOT_KEYWORDS",{hotKeywords:[]});
                }
            })
        },
        //获取搜索的菜品
        getSearchGoods(conText,payload){
            getSearchGoodsData(payload).then(res=>{
                if(res.code==200){
                    conText.commit("SET_SEARCH_GOODS",{searchGoods:res.data});
                    if(payload.success){
                        payload.success(parseInt(res.pageinfo.pagenum));
                    }
                }else{
                    conText.commit("SET_SEARCH_GOODS",{searchGoods:[]});
                }
            })
        },
        //获取搜索菜品分页数据
        getSearchGoodsPage(conText,payload){
            getSearchGoodsData(payload).then(res=>{
                if(res.code==200){
                    conText.commit("SET_SEARCH_GOODS_PAGE",{searchGoods:res.data});
                }
            })
        }

    }
}
